<template>
</template>
<script>
  // 接口api
  import API from '../api/index'
  import * as flinkStudio from '../graph/handler/studio-handler'
  import * as global from '../graph/common/common.js'

  export default {
    components: {},
    data() {
      return {
        id: '430eb7613e26cbac93c14ba6a15b67a9',
        jobName: 'testzy',
        searchName: '',
        // 表单
        form: {
          name: '',
          flag: '', // 保存表单操作行为 add edit
          type: '' // 保存资源类型
        },
        loading: false, // 加载数据时显示动效的控制
        trans: {
          type: global.TRANS_MODEL,
          image: global.TRANS_IMAGE_PATH
        },
        job: {
          type: global.JOB_MODEL,
          image: global.JOB_IMAGE_PATH
        },
        directory: {
          type: global.DIRECTORY_MODEL,
          image: global.DIRECTORY_IMAGE_PATH
        },
        repository: {
          index: true,
          columns: [
            { type: 'normal', visible: false, prop: 'id', label: 'ID', width: 100 },
            { type: 'normal', prop: 'name', label: '名称', width: 100 },
            { type: 'normal', prop: 'type', label: '类型', width: 100 },
            { type: 'normal', prop: 'realpath', label: '路径', width: 200 },
            { type: 'normal', prop: 'modifiedUser', label: '修改人', width: 100 },
            { type: 'normal', prop: 'modifiedDate', label: '修改日期', width: 180 }
          ],
          data: []
        },
        // 弹框
        dialog: {
          visible: false,
          title: ''
        },
        // 路径导航
        navigation: {
          path: '', // 记录路径
          parentPath: '',
          breadList: [], // 存放路径数据
          flag: false
        },
        createTransHandler: {},
        createJobHandler: {},
        studio: {},
        parent: {},
        treeProps: {
          label: 'name',
          children: 'children',
          isLeaf: 'leaf'
        },
        dataLoading: false,
        filterText: '',
      }
    },
    computed: {
      domHeight: {
        get() {
          return 999 // this.$store.state.common.documentClientHeight - this.$BODY_MARGIN
        }
      }
    },
    watch: {
      filterText(val) {
        this.$refs.nodeTree.filter(val)
      }
    },
    mounted() {
      this.id = this.getQueryString(window.location.href).id
      this.jobName = this.getQueryString(window.location.href).jobName
      // this.flinkOpen(this.id, this.jobName)
    },
    methods: {
      // 获取浏览器参数
      getQueryString(url) {
        const paramArr = url.slice(url.indexOf('?') + 1).split('&')
        const params = {}
        paramArr.map((param) => {
          const [key, val] = param.split('=')
          params[key] = decodeURIComponent(val)
        })
        return params
      },
      /** *
         * 初始化
         */
      init(path, createTransHandler, createJobHandler, studio) {
        this.createTransHandler = createTransHandler
        this.createJobHandler = createJobHandler
        this.studio = studio
        // this.listRepository(path)
        this.$nextTick(() => {
          if (this.$route.query && this.$route.query.name) {
            // 血缘分析跳转过来，直接打开对应转换
            const name = this.$route.query.name
            const item = {
              type: 'transformation',
              path: '/' + name,
              name: name
            }
            this.rowDbclick(item)
          }
        })
      },
      // 目录树删除修改显示
      mouseEnter(data) {
        this.$set(data, 'show', true)
      },
      mouseLeave(data) {
        this.$set(data, 'show', false)
      },
      // 关键词过滤
      filterNode(value, data) {
        if (!value) return true
        data.name = data.name || ''
        return data.name.indexOf(value) !== -1
      },
      nodeClick(data, node) {
        // if (node.level > 1) {
        //   this.navigation.parentPath = node.parent.data.path
        // }
        this.navigation.parentPath = node.data.path
        if (node.loaded) {
          // 已经加载过目录则直接加载内容
          this.listRepository(node.data.path)
        }
      },
      // 目录树加载节点
      loadNode(node, resolve) {
        if (node.level === 0) {
          return resolve([{ name: '根目录', path: '/' }])
        } else {
          this.listRepository(node.data.path).then(list => {
            resolve(list)
          })
        }
      },
      // 获取数据=======================
      // 获取目录、转换及作业列表
      // 返回目录
      async listRepository(path) {
        return
        this.dataLoading = true
        if (!path) {
          path = this.navigation.parentPath
        }
        // if (path === '/') {
        //   this.navigation.breadList = []
        //   this.navigation.parentPath = path
        // }
        var params = {
          'path': path
        }
        const dirList = []
        try {
          const res = await API.repository.list(params)
          this.repository.data = []
          for (const item of res.data) {
            if (item.type === 'directory') {
              dirList.push(item)
            } else {
              this.repository.data.push(item)
            }
          }
        } catch (error) {
          const errorResultData = error.response.data
          this.$message({
            message: errorResultData.error.message,
            type: 'warning'
          })
        }
        // .then(res => {
        //   this.repository.data = res.data
        // })
        // .catch(error => {
        //   const errorResultData = error.response.data
        //   this.$message({
        //     message: errorResultData.error.message,
        //     type: 'warning'
        //   })
        // })
        this.dataLoading = false
        return dirList
      },
      // 创建 修改====================
      // 创建目录
      createDirectory() {
        this.dialog.visible = true
        this.dialog.title = '创建目录'
        this.form.flag = 'add'
        this.form.name = ''
      },
      // =======================列表操作==============================
      // 删除==================
      async handleDelete(row) {
        const parent = row.parent
        var params = {
          'path': row.path,
          'name': row.name
        }
        if (row.type === 'directory') {
          this.deleteDirectory(params, parent)
        } else if (row.type === 'transformation') {
          this.deleteTrans(params, parent)
        } else if (row.type === 'job') {
          this.deleteJobs(params, parent)
        }
      },
      // 删除目录
      deleteDirectory(params, parent) {
        this.$confirm('确定删除该目录及其目录下的转换?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          API.repository.delDirectories(params)
            .then(res => {
              this.$refs.nodeTree.remove(params)
              this.listRepository(parent)
              this.$message({
                message: '删除成功',
                type: 'success'
              })
            })
            .catch(error => {
              this.$message({
                message: error.data.error.message,
                type: 'warning'
              })
            })
        })
      },
      // 删除转换
      deleteTrans(params, parent) {
        this.$confirm('确定删除该转换?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          API.repository.delTrans(params)
            .then(res => {
              this.listRepository(parent)
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.$http({
                url: this.$http.adornUrl('/etl/transform/name/delete'),
                method: 'post',
                data: params['name']
              })
            })
            .catch(error => {
              this.$message({
                message: error.data.error.message,
                type: 'warning'
              })
            })
        })
      },
      // 删除作业
      deleteJobs(params, parent) {
        this.$confirm('确定删除该作业?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          API.repository.delJobs(params)
            .then(res => {
              this.listRepository(parent)
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.$http({
                url: this.$http.adornUrl('/etl/transform/name/delete'),
                method: 'post',
                data: params['name']
              })
            })
            .catch(error => {
              this.$message({
                message: error.data.error.message,
                type: 'warning'
              })
            })
        })
      },
      // 修改名称
      handlerRename(row) {
        this.dialog.visible = true
        this.dialog.title = '重命名'
        this.form.name = row.name
        this.form.originalName = row.name
        this.form.flag = 'edit'
        this.form.type = row.type
        this.navigation.path = row.path
      },
      // 修改提交
      async editSubmit() {
        var params = {
          'path': this.navigation.path,
          'name': this.form.name
        }
        if (this.form.type === 'directory') {
          this.editDirectorySubmit(params)
        } else if (this.form.type === 'transformation') {
          this.editTransSubmit(params)
        } else if (this.form.type === 'job') {
          this.editJobSubmit(params)
        }
      },
      // 修改目录提交
      editDirectorySubmit(params) {
        API.repository.renameDirectory(params)
          .then(res => {
            const node = this.$refs.nodeTree.getNode(params)
            node.data.name = params.name
            const path = (node.parent.data.path === '/' ? '' : node.parent.data.path) + '/' + params.name
            if (this.navigation.parentPath === node.data.path) {
              this.navigation.parentPath = path
            }
            node.data.path = path
            node.parent.loaded = false
            node.parent.expand()
            this.dialog.visible = false
            // this.listRepository(this.navigation.parentPath)
            this.$message({
              message: '修改成功',
              type: 'success'
            })
          })
          .catch(error => {
            this.$message({
              message: error.data.error.message,
              type: 'warning'
            })
          })
      },
      // 修改转换提交
      editTransSubmit(params) {
        API.repository.renameTrans(params)
          .then(res => {
            this.dialog.visible = false
            this.listRepository(this.navigation.parentPath)
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            params['originalName'] = this.form.originalName
            this.$http({
              url: this.$http.adornUrl('/etl/transform/name/update'),
              method: 'post',
              data: params
            })
          })
          .catch(error => {
            this.$message({
              message: error.data.error.message,
              type: 'warning'
            })
          })
      },
      // 修改作业提交
      editJobSubmit(params) {
        API.repository.renameJobs(params)
          .then(res => {
            this.dialog.visible = false
            this.listRepository(this.navigation.parentPath)
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            params['originalName'] = this.form.originalName
            this.$http({
              url: this.$http.adornUrl('/etl/transform/name/update'),
              method: 'post',
              data: params
            })
          })
          .catch(error => {
            this.$message({
              message: error.data.error.message,
              type: 'warning'
            })
          })
      },
      // =======================路径跳转操作==========================
      // 路径跳转
      // async pathSkip (row) {
      //   if (row) {
      //     // 重新组织路径数据
      //     await this.putBreadData(row)
      //     // 根据路径获取列表数据
      //     await this.listRepository(row.path)
      //     this.navigation.parentPath = row.path
      //   } else {
      //     // 点击根路径
      //     this.navigation.breadList = []
      //     this.listRepository('/')
      //     this.navigation.parentPath = '/'
      //   }
      // },
      // 点击超链接跳转
      async addPath(row) {
        for (let i = 0; i < this.navigation.breadList.length; i++) {
          if (row.id === this.navigation.breadList[i].id) {
            return
          }
        }
        this.navigation.breadList.push(row)
        // 获取路径
        // const path = await this.getPath(this.navigation.breadList);
        // 根据路径获取列表数据
        this.navigation.parentPath = row.path
        await this.listRepository(row.path)
      },
      // 组织路径数据
      putBreadData(bread) {
        this.navigation.flag = false
        if (bread && bread !== '/') {
          for (let i = 0; i < this.navigation.breadList.length; i++) {
            if (bread.id === this.navigation.breadList[i].id) {
              // 当前节点为数组中最后一个节点时 不操作
              if (i === this.navigation.breadList.length - 1) {
                return
              } else {
                this.navigation.flag = true
              }
            }
            // 当前节点不是最后一个节点时，去掉后面多余节点
            if (this.navigation.flag) {
              this.navigation.breadList.pop()
            }
          }
        } else {
          // 点击根目录
          this.navigation.breadList = []
        }
      },
      // 提交
      handleSubmit() {
        if (this.form.flag === 'add') {
          this.addSubmit()
        } else if (this.form.flag === 'edit') {
          this.editSubmit()
        }
      },
      // 新增提交
      async addSubmit() {
        var params = {
          'parent': (this.$refs.nodeTree.getCurrentNode() || this.$refs.nodeTree.getNode('/')).path,
          'name': this.form.name
        }
        API.repository.create(params)
          .then(res => {
            const node = this.$refs.nodeTree.getNode(params.parent) || this.$refs.nodeTree.getNode('/')
            node.parent.loaded = false
            node.parent.expand()
            // const newChild = {
            //   path: (params.parent === '/' ? '' : params.parent) + '/' + params.name,
            //   name: params.name,
            //   children: [],
            //   type: 'directory'
            // }
            // if (!data.children) {
            //   this.$set(data, 'children', [])
            // }
            // data.children.push(newChild)
            this.dialog.visible = false
            this.listRepository(this.navigation.parentPath)
            this.$message({
              message: '创建成功',
              type: 'success'
            })
          })
          .catch(error => {
            this.$message({
              message: error.response.data.error.message,
              type: 'warning'
            })
          })
      },
      // 双击行打开资源
      async rowDbclick(row) {
        if (row.type === 'directory') {
          this.addPath(row)
        } else {
          // 打开加载动画
          this.loading = true
          // 获取xml
          let result = null
          if (row.type === 'transformation') {
            result = await studio.getTransXml(row.path, row.name)
          } else if (row.type === 'job') {
            result = await this.studio.getJobXml(row.path, row.name)
          }
          if (result.data) {

            // 根据xml加载数据
            // this.parent.openRepository_(result.data, row.type, row.path)
            this.$emit('openRepository', result.data, row.type, row.path)
            // 关闭加载动画
            this.loading = false
          }
        }
      },
      // 打开资源flink
      async flinkOpen(id, jobName) {
        this.loading = true
        // 获取xml
        let result = null
        result = await flinkStudio.flinkGetTransXml(id, jobName)
        if (result.data) {
          // 根据xml加载数据
          // this.parent.openRepository_(result.data, 'transformation', jobName)
          this.$emit('openRepository', result.data, 'transformation', jobName)
          // 关闭加载动画
          this.loading = false
        }
      },
      // // 打开资源
      openRepository(xml, type, path) {
        this.$emit('openRepository_', xml, type, path)
      }
    }
  }
  </script>

